<template>
  <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="min-fill-page energy-list">
    <dataDisplay
      v-if="tabStatus === 3"
      :data-list="displayData"
      class="mobile-data"
      style="margin-bottom:16px;"
    />
    <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
      <FilterInput
        ref="FilterToolRef"
        v-model="paramsObj"
        :filter-list="filterList"
        show-search-btn
        is-show-config
        @handelClick="queryClick"
        @queryEmpty="queryEmpty"
        @filterTagStatus="filterTagStatus"
      />
      <div class="extra-filter-box">
        <el-checkbox v-model="isRepeatLink" style="margin-right: 20px;" @change="queryClick">重复链接</el-checkbox>
      </div>
      <div class="opeator-bar">
        <createBtn v-if="hasRouteAuth('publish:publishList:createOrImport')" style="margin-right:10px;" text="新建链接" @click.native="createLink"/>
        <MoreOpeator
          ref="moreOpeatorRef"
          :list="[
            {label: '导出', exportApi:'/admin/publish/list/export', auth: hasRouteAuth('publish:publishList:export'), type: 'export', exportName: '发布信息', isBeforeExport: true, beforeExport: exportBeforeExport, refName: 'exportRef' },
            {label: '批量导入', type: 'import', callback: fetchData, importApi: '/admin/publish/import', auth: hasRouteAuth('publish:publishList:createOrImport')},
            {label: '下载导入模板', type: 'export', exportName: '导入模板', exportApi: '/admin/publish/template/export'}
          ]"
          style="margin-right:10px;"
        />
      </div>
    </div>
    <div class="table-list">
      <div v-loading="listLoading" style="min-height: 300px">
        <u-table
          v-if="list.items.length"
          ref="publishList"
          :data="list.items"
          :border="true"
          :height="setTableHeight"
          :row-height="rowHeight(56)"
          :row-class-name="(data) => tableRowClassName(data)"
          beautify-table
          header-drag-style
          row-key="id"
          use-virtual
          element-loading-text="加载中..."
          empty-text="暂无数据"
          fit
          class="fb-table"
          header-cell-class-name="order-data-header-cell"
          @select="selectTable"
          @select-all="selectTable"
          @sort-change="sortMethod"
        >
          <u-table-column :reserve-selection="true" :fixed="selectFixed" align="center" type="selection" width="50" />
          <u-table-column :fixed="selectFixed" align="left" label="账号" min-width="100">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.account" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="下单平台" min-width="120">
            <template slot-scope="scope">
              <div :class="{ 'gray-filter': scope.row.status === 0 }" class="flex-center">
                <platformIcon :data="scope.row.platformTypeName" />
                {{ scope.row.platformTypeName || '--' }}
              </div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="品牌名称" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.brandName" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="发布链接" min-width="120" prop="publishUrl" sortable="custom">
            <template slot-scope="scope">
              <el-tooltip
                v-if="scope.row.publishUrl && (scope.row.publishUrl.indexOf('http://') === 0 || scope.row.publishUrl.indexOf('https://') === 0)"
                :open-delay="800"
                class="item"
                placement="top"
                effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.publishUrl }}</div>
                <a
                  :href="scope.row.publishUrl"
                  target="_blank"
                  class="link-name light-word">
                  点击跳转<img src="../../../assets/medium/publish-link.png" alt="link-icon">
                </a>
              </el-tooltip>
              <ToolTip v-else :content="scope.row.publishUrl" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="发布文案" min-width="150">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.publishRemark" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="重复链接" min-width="80">
            <template slot-scope="scope">
              <StatusText
                v-if="typeof scope.row.isRepeatLink === 'boolean'"
                :color="scope.row.isRepeatLink ? '#FF504F' : '#31cc9c'"
                :text="scope.row.isRepeatLink ? '是' : '否'" />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="发布数据" min-width="355">
            <template slot-scope="scope">
              <div v-if="showPublishData(scope.row.platformTypeName)" class="publish-data">
                <span
                  v-for="(item, index) in getPublishDataIcon(scope.row.platformTypeName)"
                  :key="index"
                  :class="{'last-item': index === 2}"
                  :style="{ marginLeft: scope.row.publishUrl ? '0' : '20px'}"
                  class="publish-data-item">
                  {{ item.tip }} : {{ scope.row.publishData[item.key] | bigDataFilter }}
                </span>
              </div>
              <div v-else>暂不采集</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="采集次数" min-width="100">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.pickCount" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="采集成功次数" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.pickSuccessCount" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="发布时间" width="150" prop="publishTime" sortable="custom">
            <template slot-scope="scope">
              <div>{{ format(scope.row.publishTime, 'YYYY/MM/DD HH:mm') }}</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="发布截图" min-width="300">
            <template slot-scope="scope">
              <div class="flex">
                <FileShowList
                  ref="fileshowRef"
                  :file-list="scope.row.attachment"
                  :table-single="true"
                  :show-image="true"
                  :single-row-img="false"
                  :show-pick="scope.row.pickStatus !== 2 && hasRouteAuth('publish:screenshot:manage')"
                  :show-delete="hasRouteAuth('publish:screenshot:manage') && scope.row.attachment && scope.row.attachment.length > 1"
                  is-show-single-file
                  @pickFile="handleImage($event, 1, 0, scope.row.id)"
                  @removeFileList="handleImage($event, 0, 0, scope.row.id)"
                />
                <el-button
                  v-if="scope.row.pickStatus !== 2 && hasRouteAuth('publish:screenshot:manage') && scope.row.attachment && scope.row.attachment.length === 1"
                  :loading="scope.row.pickLoading"
                  class="ml10"
                  size="small"
                  type="text"
                  @click="handlePick(scope.row, 1)">采集</el-button>
              </div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="采集状态" min-width="110">
            <template slot-scope="scope">
              <StatusText
                :color="getPickStatusColor(scope.row.pickStatus)"
                :text="scope.row.pickStatus | getPickStatus" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="采集有效时间" min-width="150" prop="collectExpirationTime" sortable="custom">
            <template slot-scope="scope">
              <ToolTip :content="format(scope.row.collectExpirationTime, 'YYYY/MM/DD HH:mm')" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="运营人员">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.accountOperationName" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="所属经营体" width="120">
            <template slot-scope="scope">
              <el-tooltip
                v-if="scope.row.resourceAttributionMatrix"
                :open-delay="800"
                class="item"
                placement="top"
                effect="dark">
                <div slot="content" style="max-width: 200px">{{ scope.row.entityTip }}</div>
                <div class="resource-name ellipsisOne" style="max-width: 120px">{{ scope.row.resourceAttributionMatrix }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="订单编号" width="150">
            <template slot-scope="scope">
              <el-tooltip
                v-if="scope.row.sn"
                :open-delay="800"
                class="item"
                placement="top"
                effect="dark">
                <div slot="content" style="max-width: 200px">{{ scope.row.sn }}</div>
                <div
                  :class="{'light-word':hasRouteAuth('publish:publishList:goToOrder')}"
                  class="resource-name ellipsisOne pointer"
                  style="max-width: 120px"
                  @click="toOrderDetail(scope.row)">
                  {{ scope.row.sn }}
                </div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="订单状态" min-width="80">
            <template slot-scope="scope">
              <div v-if="scope.row.orderStatus || scope.row.orderStatus === 0" >
                <div style="display:flex;align-items:center;">
                  <span :style="{backgroundColor: getColor(scope.row.orderStatus)}" class="dot"/>
                  {{ scope.row.orderStatus | orderStatusFilter }}
                </div>
              </div>
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column align="left" label="项目名称">
            <template slot-scope="scope">
              <div v-if="scope.row.projectName" :class="{'light-word pointer': scope.row.reportId}" @click="toReportDetail(scope.row)">
                <ToolTip :content="scope.row.projectName" />
              </div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建人" min-width="100">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.creator" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="所属部门" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.department" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建时间" min-width="150" prop="createTime" sortable="custom">
            <template slot-scope="scope">
              <ToolTip :content="format(scope.row.createTime, 'YYYY/MM/DD HH:mm')" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="更新时间" min-width="150" prop="updateTime" sortable="custom">
            <template slot-scope="scope">
              <ToolTip :content="format(scope.row.updateTime, 'YYYY/MM/DD HH:mm')" />
            </template>
          </u-table-column>
        </u-table>
        <EmptyPlaceholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
      </div>
      <CreateLinkDialog :visible="linkVisible" @updateData="fetchData()" @closeDialog="()=>{linkVisible=false}"/>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <el-pagination
          v-show="list.total > 0"
          :current-page.sync="page"
          :page-size="perPage"
          :total="list.total"
          :small="true"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <fixed-pagination v-show="list.total > 0">
        <template v-if="showMobilePage">
          <FilterInput
            ref="FilterToolRef"
            v-model="paramsObj"
            :filter-list="filterList"
            show-search-btn
            is-show-config
            show-mobile-icon
            @handelClick="queryClick"
            @queryEmpty="queryEmpty"
            @filterTagStatus="filterTagStatus">
            <div slot="checkGroup">
              <el-checkbox v-model="isRepeatLink" style="margin-right: 20px;" @change="queryClick">重复链接</el-checkbox>
            </div>
          </FilterInput>
          <MoreOpeator
            ref="moreOpeatorRef"
            :list="[
              {label: '导出', exportApi:'/admin/publish/list/export', auth: hasRouteAuth('publish:publishList:export'), type: 'export', exportName: '发布信息', isBeforeExport: true, beforeExport: exportBeforeExport, refName: 'exportRef' },
              {label: '批量导入', type: 'import', callback: fetchData, importApi: '/admin/publish/import'},
              {label: '下载导入模板', type: 'export', exportName: '导入模板', exportApi: '/admin/publish/template/export'},
              { status: 1, label: '加入采集', auth: hasRouteAuth('publish:publishList:addPick')},
              { status: 2, label: '停止采集', auth: hasRouteAuth('publish:publishList:stopPick')},
              { status: 3, label: '完成采集', auth: hasRouteAuth('publish:publishList:completePick')},
              { status: 4, label: '删除', auth: hasRouteAuth('publish:publishList:delete')}
            ]"
            :handel-click="pickOperate"
            style="margin-right:10px;"
            show-mobile-icon
          />
          <createBtn v-if="hasRouteAuth('publish:publishList:createOrImport')" mobile-table text="新建链接" @click.native="createLink" />
        </template>
        <div v-if="!showMobilePage" class="delete-button-container" style="flex: 1">
          <MoreOpeator
            v-if="hasRouteAuth('publish:publishList:addPick') || hasRouteAuth('publish:publishList:stopPick') || hasRouteAuth('publish:publishList:completePick')"
            :list="[
              { status: 1, label: '加入采集', auth: hasRouteAuth('publish:publishList:addPick')},
              { status: 2, label: '停止采集', auth: hasRouteAuth('publish:publishList:stopPick')},
              { status: 3, label: '完成采集', auth: hasRouteAuth('publish:publishList:completePick')},
              { status: 4, label: '删除', auth: hasRouteAuth('publish:publishList:delete')}
            ]"
            :handel-click="pickOperate"
            label="批量操作"
            style="margin-right:14px;"
          />
          <div style="flex:1;" class="flex-center">
            <div v-if="selectData.length" class="select-box-style">
              <span class="select-data-num">已选 <span>{{ selectData.length }}</span> 条</span>
              <el-button type="text" @click="clearSelect"><span class="el-icon-close"/></el-button>
            </div>
          </div>
        </div>
        <el-pagination
          v-if="!showMobilePage"
          v-show="list.total > 0"
          :current-page.sync="page"
          :page-size="perPage"
          :total="list.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          layout="total, prev, pager, next, sizes, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </fixed-pagination>
    </div>
  </div>
</template>

<script>
import axios from 'axios'; // 取消未完成请求
import { mapState } from 'vuex';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import createBtn from '@/components/Common/baseComponent/createBtn';
import FileShowList from '@/components/CreateOrder/fileShowList';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import platformIcon from '@/components/Common/platformIcon';
import ListTab from '@/components/ListTab';
import CreateLinkDialog from './createLinkDialog';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import { getPublishList, getPublishTab, putPublishStatus, putPublishStatusValid, deleteLink,
  imageRePick, delImage, getStatistics } from '@/api/publish';
import { getDepartmentAll } from '@/api/config';
import { platformList } from '@/api/select';
import { getPickStatus, getPickStatusColor } from '@/filters/status';
import { getDeptFullName } from '@/filters/dept';
import { bigDataFilter } from '@/filters/number';
import { format } from '@/filters/date';
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
import { hasRouteAuth } from '@/utils/permission';
import ElMessage from '@/utils/message';
import { showModal } from '@/utils/message';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import defaultIcon from '@/assets/lookData.png';

import { enter2Br } from '@/utils/string';

export default {
  filters: {
    getPickStatus,
    getDeptFullName,
    bigDataFilter,
    orderStatusFilter(status) {
      // orderStatus 0:草稿中 1:待发布 3:待审批 4:待封账 5:封账中 6:已封账 7:已完成
      const arr = ['草稿中', '待发布', '待核算', '待审批', '待封账', '封账中', '已封账', '已完成'];
      return arr[Number(status)];
    }
  },
  components: {
    ListTab,
    EmptyPlaceholder,
    createBtn,
    FileShowList,
    btnGroup,
    platformIcon,
    MoreOpeator,
    CreateLinkDialog,
    dataDisplay
  },
  mixins: [TableAdaptive, mobileTable],
  data() {
    return {
      defaultIcon,
      list: {
        items: [],
        total: 0,
        isInit: true
      },
      tabStatus: -1,
      page: 1,
      perPage: 20,
      sortType: '',
      sortName: '',
      paramsObj: {},
      listLoading: false,
      deptTreeList: [],
      cancelToken: null,
      orderPlatformOption: [],
      ids: '',
      selectData: [],
      selectDataObj: [],
      publishUrl: '',
      rangeKeyArr: [
        { attr: 'read', start: 'readStart', end: 'readEnd', type: 'number' },
        { attr: 'like', start: 'likeStart', end: 'likeEnd', type: 'number' },
        { attr: 'share', start: 'shareStart', end: 'shareEnd', type: 'number' },
        { attr: 'comment', start: 'commentStart', end: 'commentEnd', type: 'number' },
        { attr: 'look', start: 'lookStart', end: 'lookEnd', type: 'number' },
        { attr: 'collect', start: 'collectStart', end: 'collectEnd', type: 'number' },
        { attr: 'publishTime', start: 'publishStartTime', end: 'publishEndTime', type: 'time' },
        { attr: 'createTime', start: 'createStartTime', end: 'createEndTime', type: 'time' },
        { attr: 'updateTime', start: 'updateStartTime', end: 'updateEndTime', type: 'time' },
        { attr: 'collectExpirationTime', start: 'collectExpirationStartTime', end: 'collectExpirationEndTime', type: 'time' }
      ],
      arrayKeyArr: ['attributionMatrixId', 'platformId', 'orderStatus'],
      orderMode: 0,
      linkVisible: false,
      isRepeatLink: false,
      statisticalData: {
        invalidLink: null,
        failed: null
      }
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    }),
    filterList() {
      const arr = [
        { keyword: 'account', name: '账号', type: 'input', labelWidth: '70px' },
        { keyword: 'publishUrl', name: '发布链接', type: 'input', labelWidth: '70px' },
        { keyword: 'publishRemark', name: '发布文案', type: 'input', labelWidth: '70px' },
        { keyword: 'accountOperationName', name: '运营人员', type: 'input', labelWidth: '70px' },
        { keyword: 'sn', name: '订单编号', type: 'input', labelWidth: '70px' },
        { keyword: 'brandName', name: '品牌名称', type: 'input', labelWidth: '70px' },
        { keyword: 'creator', name: '创建人', type: 'input', labelWidth: '70px' },
        { keyword: 'read', name: '阅读', type: 'inputRange', labelWidth: '70px', startPlaceholder: '最低数值', endPlaceholder: '最高数值' },
        { keyword: 'like', name: '点赞', type: 'inputRange', labelWidth: '70px', startPlaceholder: '最低数值', endPlaceholder: '最高数值' },
        { keyword: 'share', name: '转发', type: 'inputRange', labelWidth: '70px', startPlaceholder: '最低数值', endPlaceholder: '最高数值' },
        { keyword: 'comment', name: '评论', type: 'inputRange', labelWidth: '70px', startPlaceholder: '最低数值', endPlaceholder: '最高数值' },
        { keyword: 'look', name: '在看', type: 'inputRange', labelWidth: '70px', startPlaceholder: '最低数值', endPlaceholder: '最高数值' },
        { keyword: 'collect', name: '收藏', type: 'inputRange', labelWidth: '70px', startPlaceholder: '最低数值', endPlaceholder: '最高数值' },
        { keyword: 'publishTime', name: '发布时间', labelWidth: '70px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'collectExpirationTime', name: '采集有效时间', labelWidth: '70px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'createTime', name: '创建时间', labelWidth: '70px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'updateTime', name: '更新时间', labelWidth: '70px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'platformId', name: '下单平台', type: 'mulSelect', options: this.orderPlatformOption },
        { keyword: 'attributionMatrixId', name: '所属经营体', type: 'cascaderSelectWithChild',
          childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'departmentId', name: '所属部门', type: 'cascaderSelect', childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'hasScreenshots', name: '是否有截图', type: 'select', options: [
          { value: true, label: '是' }, { value: false, label: '否' }
        ] },
        { keyword: 'hasData', name: '是否有数据', type: 'select', options: [
          { value: true, label: '是' }, { value: false, label: '否' }
        ] },
        { keyword: 'isRelatedOrder', name: '是否关联订单', type: 'select', options: [
          { value: 1, label: '是' }, { value: 0, label: '否' }
        ] },
        { keyword: 'orderStatus', name: '订单状态', type: 'mulSelect', options: [
          { value: 0, label: '草稿中' }, { value: 1, label: '待发布' }, { value: 3, label: '待审批' }, { value: 4, label: '待封账' }, { value: 5, label: '封账中' }, { value: 6, label: '已封账' }, { value: 7, label: '已完成' }
        ] }
      ];
      return arr;
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 200 : 0;
    },
    displayData() {
      return [
        { data: this.statisticalData.invalidLink, label: '无效链接', isMoney: false },
        { data: this.statisticalData.failed, label: '未成功采集', isMoney: false }
      ];
    }
  },
  created() {
    const query = this.$route.query;
    if (query.publishUrl) {
      this.$set(this.paramsObj, 'publishUrl', query.publishUrl);
    }
    this.clearSelectData();
    this.queryDeptTreeList();
    this.platformList();
    this.fetchData();
  },
  methods: {
    hasRouteAuth,
    format,
    getPickStatusColor,
    getColor(status) {
      // 订单状态： 0: 草稿中 1: 待发布 3: 待审批 4: 待封账 5: 封账中 6: 已封账 7: 已完成
      let color = '';
      switch (status) {
        case 0:
          color = '#406EFF';
          break;
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
          color = '#FD8546';
          break;
        case 6:
        case 7:
          color = '#31CC9C';
          break;
      }
      return color;
    },
    changeOrderMode(val) {
      this.orderMode = val;
      this.fetchData(true);
    },
    showPublishData(p) {
      return ['微信', '小红书', '微博', '抖音'].includes(p);
    },
    getPublishDataIcon(platform) {
      return {
        '微信': [
          { key: 'read', icon: 'read', tip: '阅读' },
          { key: 'like', icon: 'like', tip: '点赞' },
          { key: 'look', icon: 'look', tip: '在看' }
        ],
        '小红书': [
          { key: 'like', icon: 'like', tip: '点赞' },
          { key: 'comment', icon: 'comment', tip: '评论' },
          { key: 'collect', icon: 'collect', tip: '收藏' }
        ],
        '微博': [
          { key: 'like', icon: 'like', tip: '点赞' },
          { key: 'comment', icon: 'comment', tip: '评论' },
          { key: 'share', icon: 'share', tip: '转发' }
        ],
        '抖音': [
          { key: 'like', icon: 'like', tip: '点赞' },
          { key: 'comment', icon: 'comment', tip: '评论' },
          { key: 'share', icon: 'share', tip: '转发' }
        ]
      }[platform];
    },
    getTabs() {
      const params = this.getParams();
      getPublishTab(params).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        res.data.push({ name: '图片列表', id: -2 });
        this.$emit('getTabs', res.data || []);
      }).catch(err => {
        console.log(err);
      });
    },
    toOrderDetail(row) {
      if (!hasRouteAuth('publish:publishList:goToOrder')) {
        return;
      }
      let url;
      if (row.category === 1) {
        url = this.$router.resolve({
          name: 'projectChildDetail',
          params: { id: row.orderId }
        });
      } else if (row.category === 0) {
        url = this.$router.resolve({
          name: 'orderDetail',
          params: { orderId: row.orderId }
        });
      }
      url && window.open(url.href, '_blank');
    },
    toReportDetail(row) {
      if (row.reportId) {
        const routeUrl = this.$router.resolve({
          name: 'publishDetail',
          params: { id: row.reportId }
        });
        window.open(routeUrl.href, '_blank');
      }
    },
    // 选择表格
    selectTable(e) {
      this.selectData = e.map(item => { return item.id; });
      this.selectDataObj = e;
      this.ids = this.selectData.join(',');
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    exportBeforeExport() {
      const params = this.getParams();
      params.tabStatus = this.tabStatus;
      params.ids = this.ids;
      if (this.$refs.moreOpeatorRef) {
        this.$refs.moreOpeatorRef.btnExport(params, 'exportRef');
      }
    },
    getParams() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      if (this.sortType || this.sortName) {
        params.sortName = this.sortName;
        params.sortType = this.sortType;
      }
      params.isRepeatLink = this.isRepeatLink;
      return params;
    },
    clearSelect() {
      showModal('是否清空已勾选的数据？', '').then(() => {
        this.clearSelectData();
        this.$refs.publishList.clearSelection();
      });
    },
    clearSelectData() {
      this.selectData = [];
      this.selectDataObj = [];
      this.ids = '';
      if (this.$refs.publishList && this.$refs.publishList.clearSelection) {
        this.$refs.publishList.clearSelection();
      }
    },
    clearMixinSelection() {
      this.selectData = [];
      this.selectDataObj = [];
      this.ids = '';
      if (this.$refs.publishList && this.$refs.publishList.clearMixinSelection) {
        this.$refs.publishList.clearMixinSelection();
      }
    },
    async platformList() {
      try {
        const result = await platformList();
        result.data = result.data.map(item => {
          item = {
            value: item.id,
            label: item.value
          };
          return item;
        });
        result.data.unshift({ value: -2, label: '--' });
        this.orderPlatformOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    queryDeptTreeList() {
      getDepartmentAll()
        .then(res => {
          this.deptTreeList = (res && res.data) || [];
        })
        .catch(e => {
          console.log(e);
        });
    },
    handleTabClick(id) {
      this.tabStatus = id;
      if (id === -2) return;
      this.list = { items: [] };
      this.clearSelectData();
      this.fetchData(true);
    },
    getStatistics(params) {
      getStatistics(params).then(res => {
        if (res.code === 200 && res.data) {
          this.statisticalData = res.data;
        } else {
          this.statisticalData = {};
        }
      });
    },
    fetchData(reset = false) {
      if (this.cancelToken) this.cancelToken.cancel('cancel');
      const source = axios.CancelToken.source(); // 用于取消请求
      this.cancelToken = source;
      this.getTabs();
      this.listLoading = true;
      if (reset) this.page = 1;
      let params = this.getParams();
      params = {
        ...params,
        page: this.page,
        perPage: this.perPage,
        tabStatus: this.tabStatus
      };
      if (this.tabStatus === 3) {
        this.getStatistics(params);
      }
      getPublishList(params, source.token).then(res => {
        this.listLoading = false;
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.list = res.data;
        this.list.items.forEach(cur => {
          this.$set(cur, 'pickLoading', false);
          if (cur.pickStatus !== 2 && cur.attachment && cur.attachment.length > 1) {
            cur.attachment.forEach(ele => {
              this.$set(ele, 'pickLoading', false);
              this.$set(ele, 'delLoading', false);
            });
          }
        });
        this.list.isInit = false;
      }).catch(err => {
        this.listLoading = false;
        console.log(err);
      });
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.isRepeatLink = false;
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    stopPickCheck() {
      const statusArr = [...new Set(this.selectDataObj.map(it => it.pickStatus))];
      let result = false;
      if (statusArr.includes(1)) {
        ElMessage.error('采集状态为已完成的发布链接不可设置【停止采集】');
        result = true;
      }
      /* if (statusArr.some(it => ![0, 2, 3, 4].includes(it))) {
        ElMessage.error('仅采集状态为：待采集/采集中/采集失败的链接可以设置【停止采集】');
        result = true;
      } */
      return result;
    },
    async pickOperate(i) {
      if (this.selectData.length === 0) {
        ElMessage.warning('请选择发布信息');
        return;
      }
      if (i.status === 4) {
        showModal('是否删除当前选择的内容？', '').then(() => {
          const params = { ids: this.selectData.join() };
          deleteLink(params).then(res => {
            if (res.code === 200) {
              if (this.page > 1 && this.perPage * (this.page - 1) + this.selectData.length === this.list.total) {
                this.page--;
              }
              this.fetchData();
              this.clearSelectData();
              ElMessage.success(res.message);
            } else {
              ElMessage.error(res.message);
            }
          }).catch(err => {
            console.log(err);
          });
        });
      } else {
        if (i.status === 2) {
          const res = this.stopPickCheck();
          if (res) return;
        }
        const params = {
          status: i.status,
          ids: this.selectData
        };
        try {
          const res = await putPublishStatus(params);
          if (res.code === 200) {
            if (this.page > 1 && this.perPage * (this.page - 1) + this.selectData.length === this.list.total) {
              this.page--;
            }
            this.fetchData();
            this.clearSelectData();
            ElMessage.success(res.message);
          } else {
            ElMessage.error(res.message);
          }
        } catch (err) {
          if (i.status === 1) {
            this.confirm(err.message, params);
          } else {
            ElMessage.error(err.message);
          }
        }
      }
    },
    confirm(message, data) {
      showModal(enter2Br(message), '', {
        confirmButtonText: '仅提交符合内容',
        cancelButtonText: '取消',
        showCancelButton: true,
        showClose: true,
        type: 'warning',
        center: true,
        iconClass: 'charge-icon',
        cancelButtonClass: 'btn-custom-cancel',
        customClass: `charge-message-box publish-err-message-box ${this.showMobilePage ? 'charge-mobile' : ''}`,
        dangerouslyUseHTMLString: true
      }).then(() => {
        putPublishStatusValid(data).then(res => {
          if (res.code === 200) {
            this.fetchData();
            this.clearSelectData();
            ElMessage.success(res.message);
          } else {
            ElMessage.error(res.message);
          }
        });
      });
    },
    tableRowClassName({ row, rowIndex }) {
      if (this.selectData && this.selectData.length > 0) {
        const ids = this.selectData;
        return ids.includes(row['id']) ? `table-selected` : '';
      }
      return '';
    },
    createLink() {
      this.linkVisible = true;
    },
    closeLinkDialog() {
      this.linkVisible = false;
    },
    handleImage(val, type, isRowClick, id) {
      if (type) {
        this.handlePick(val, isRowClick, id);
      } else {
        this.handleDelete(val, id);
      }
    },
    handlePick(row, isRowClick = 0, id = '') {
      showModal('请确认是否进行重新采集', '', {}, true).then(() => {
        let params = {};
        if (isRowClick) { // 行点击
          row.pickLoading = true;
          params = { id: row.id, imageName: row.attachment[0].name };
        } else { // 附件点击
          row.file.pickLoading = true;
          params = { id, imageName: row.file.name };
        }
        imageRePick(params).then(res => {
          if (res.code === 200) {
            ElMessage.success('修改成功！');
            this.fetchData();
          }
        }).finally(_ => {
          if (isRowClick) {
            row.pickLoading = false;
          } else {
            row.file.pickLoading = false;
            this.$refs['fileshowRef'].closeDialog();
          }
        });
      }).catch(() => {
        isRowClick ? row.pickLoading = false : row.file.pickLoading = false;
      });
    },
    handleDelete(row, id = '') {
      showModal('请确认是否删除该图片', '').then(() => {
        row.file.delLoading = true;
        const params = { id, imageName: row.file.name };
        delImage(params).then(res => {
          if (res.code === 200) {
            ElMessage.success('修改成功！');
            this.fetchData();
          }
        }).finally(_ => {
          this.$refs['fileshowRef'].closeDialog();
          row.file.delLoading = true;
        });
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.energy-list {
  margin: 16px 16px 0 16px;
  background-color: #fff;
  padding: 20px 24px 55px 24px;
}
.pointer {
  cursor: pointer;
}
.opeator-bar {
  position: absolute;
  right: 0;
  top: 0;
  display: flex;
  align-items: center;
}
.delete-button-container {
  flex:1;
  height: 32px;
  display: flex;
  align-items: center;
}
.light-word{
  color: #406eff;
}
.link-name{
  display: flex;
  align-items: center;
  img{
    width: 14px;
    height: 15px;
    margin-left: 4px;
  }
}
.publish-data{
  display: flex;
  align-items: center;
  img{
    width: 16px;
    height: 16px;
    margin-right: 4px;
  }
  .img-container {
    display: flex;
  }
  .ml20 {
    margin-left: 20px;
  }
}
.publish-data-item{
  display: inline-block;
  width: 108px;
  &.last-item{
    width: 93px;
  }
}
.select-box-style{
  height: 30px;
  line-height: 30px;
  display: flex;
  align-items: center;
  background-color: #fafafc;
  padding: 5px 12px;
  text-align: center;
  font-size: 14px;
  color: #666;
  .select-data-num{
    display: inline-block;
    margin-right: 5px;
    span{
      color: #406eff;
      font-size: 14px;
      font-weight: 600;
    }
  }
}
.ml10 {
  margin-left: 10px;
}
.filter {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  position: relative;
}
.extra-filter-box {
  position: absolute;
  left: 509px;
  top: 6px;
  display:flex;
  align-items:center;
}
</style>
<style lang="scss">
.publish-err-message-box {
  .el-message-box__btns {
    display: flex;
    justify-content: center;
    flex-flow: row-reverse;
    .el-button--small {
      width: auto !important;
      margin-left: 0px;
    }
    .el-button--primary {
      margin-right: 10px;
    }
    .btn-custom-cancel {
      margin-left: 10px;
    }
  }
}
.charge-mobile {
  width: 100% !important;
}
.dot {
  width: 4px;
  height: 4px;
  border-radius: 50%;
  margin-right: 5px;
}
</style>
